//
//  BFShShopCarViewController.m
//  BeautyFood
//
//  Created by imac on 2020/4/26.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THShopCarViewController.h"
#import "BFShShopCarTableViewCell.h"
@interface THShopCarViewController ()
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**<  */
@property(nonatomic, strong) STButton                     *editButton;/**<  */
@property(nonatomic, strong) STButton                     *allButton;/**<  */

@property(nonatomic, strong) STLabel                     *priceLable;/**<  */
@property(nonatomic, strong) STLabel                     *postLable;/**<  */
@property(nonatomic, strong) UIView                     *bootom_view;/**<  */
@end

@implementation THShopCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [BFShShopCarDataController stoneobs_fun_update_shopcarcount_ifNeed];
    [self stoneobs_fun_st_autoAdjustAllResponder];
    self.title = @"购物车";
    ({
        __weak typeof(self) weakSelf =  self;
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                                  title:@"编辑"
                                                             titleColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                                              titleFont:15
                                                           cornerRadius:0
                                                        backgroundColor:nil
                                                        backgroundImage:nil
                                                                  image:nil];
        [stoneobs_ui_button setTitle:@"完成" forState:UIControlStateSelected];
        [self stoneobs_fun_st_setRightItemWithView:stoneobs_ui_button];
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            [weakSelf stoneobs_fun_st_rightBarAction:nil];
        }];
        self.editButton = stoneobs_ui_button;
    });
    
    
    __weak typeof(self) weakSelf =  self;
    self.tableView.st_noreslutView = [[STTools_NoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 30, STONEOBS_UI_UISCREEN_WIDTH, 400) title:@"" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf stoneobs_fun_send_list_request];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    
    [self stoneobs_ui_config_bootom_view];
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.frame = CGRectMake(0, TMUtils.stoneobs_fun_get_navgationBarBootom, STONEOBS_UI_UISCREEN_WIDTH, self.bootom_view.top - TMUtils.stoneobs_fun_get_navgationBarBootom);


    
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.didLoad) {
        self.page =  1;
        [self stoneobs_fun_send_list_request];
    }
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)stoneobs_ui_config_bootom_view{
    self.bootom_view = [UIView.alloc initWithFrame:CGRectMake(0, 0, STONEOBS_UI_UISCREEN_WIDTH, 55)];
    self.bootom_view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.bootom_view];
    self.bootom_view.bottom = TMUtils.stoneobs_fun_get_tabBarTop;
    if (self.rt_navigationController.childViewControllers.count > 1) {
        self.bootom_view.top = TMUtils.stoneobs_fun_get_tabBarTop;
    }
    __weak typeof(self) weakSelf =  self;
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 80, 55)
                                                              title:@"全选"
                                                         titleColor:STONEOBS_UI_SECEND_TEXT_COLOR
                                                          titleFont:15
                                                       cornerRadius:0
                                                    backgroundColor:nil
                                                    backgroundImage:nil
                                                              image:[UIImage imageNamed:@"wgx"]];
    [stoneobs_ui_button setImage:[UIImage imageNamed:@"gx"] forState:UIControlStateSelected];
    stoneobs_ui_button.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [self.bootom_view addSubview:stoneobs_ui_button];
    self.allButton = stoneobs_ui_button;
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {
        sender.selected = !sender.selected;
        for (BFShShopCarModel * model in weakSelf.dataSouce) {
            model.cus_selected = sender.selected;
        }
        [weakSelf.tableView reloadData];
        [weakSelf stoneobs_fun_update_price_and_allButton_status];
    }];
    ({
        STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 55)
                                                                text:@""
                                                           textColor:STONEOBS_UI_SECEND_TEXT_COLOR
                                                                font:12
                                                         isSizetoFit:NO
                                                       textAlignment:NSTextAlignmentLeft];
        [self.bootom_view addSubview:stoneobs_ui_label];
        stoneobs_ui_label.left = self.allButton.right;
        stoneobs_ui_label.backgroundColor = UIColor.clearColor;
        self.postLable = stoneobs_ui_label;
    });
    
    STLabel * stoneobs_ui_label = [[STLabel alloc] initWithFrame:CGRectMake(0, 0, 100, 55)
                                                            text:@""
                                                       textColor:STONEOBS_UI_THIRD_TEXT_COLOR
                                                            font:15
                                                     isSizetoFit:NO
                                                   textAlignment:NSTextAlignmentRight];
    [self.bootom_view addSubview:stoneobs_ui_label];
    stoneobs_ui_label.right = STONEOBS_UI_UISCREEN_WIDTH - 109 - 10 - 10;
    self.priceLable = stoneobs_ui_label;
    stoneobs_ui_label.backgroundColor = UIColor.clearColor;
    
    [self stoneobs_ui_refresh_bootom_view];
}
- (void)stoneobs_ui_refresh_bootom_view{
    [self.bootom_view addSubview:self.allButton];
    [self.bootom_view addSubview:self.priceLable];
    [self.bootom_view addSubview:self.postLable];
    __weak typeof(self) weakSelf =  self;
    

    if (!self.editButton.selected) {
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 109, 40)
                                                                  title:@"去结算"
                                                             titleColor:UIColor.whiteColor
                                                              titleFont:18
                                                           cornerRadius:20
                                                        backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                                        backgroundImage:nil
                                                                  image:nil];
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [self.bootom_view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.right = STONEOBS_UI_UISCREEN_WIDTH - 10;
        stoneobs_ui_button.centerY = self.bootom_view.height / 2;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            NSArray * array = [weakSelf stoneobs_fun_get_selctedids];
            if (array.count == 0) {
                [SVProgressHUD showInfoWithStatus:@"请选择商品"];
            }else{
                NSMutableArray * dataSouce = NSMutableArray.new;
                for (BFShShopCarModel * model in self.dataSouce) {
                    if (model.cus_selected) {
                        [dataSouce addObject:model];
                    }
                }
                THCommitOrderViewController * vc = THCommitOrderViewController.new;
                vc.dataSouce = dataSouce;
                [self pushViewController:vc animated:1];
            }
        }];
    }else{
        STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 109, 40)
                                                                  title:@"删除"
                                                             titleColor:UIColor.whiteColor
                                                              titleFont:18
                                                           cornerRadius:20
                                                        backgroundColor:STONEOBS_UI_THEME_BACKGROUNDCOLOR
                                                        backgroundImage:nil
                                                                  image:nil];
        stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [self.bootom_view addSubview:stoneobs_ui_button];
        stoneobs_ui_button.backgroundColor = [UIColor colorWithGradientStyle:UIGradientStyleTopToBottom withFrame:stoneobs_ui_button.bounds andColors:@[WH_UICOLOR_FROM_RGBA(0xFF5525),WH_UICOLOR_FROM_RGBA(0xFF2029)]];
        stoneobs_ui_button.right = STONEOBS_UI_UISCREEN_WIDTH - 10;
        stoneobs_ui_button.centerY = self.bootom_view.height / 2;
        [stoneobs_ui_button setClicAction:^(UIButton *sender) {
            NSArray * array = [weakSelf stoneobs_fun_get_selctedids];
            if (array.count == 0) {
                [SVProgressHUD showInfoWithStatus:@"请选择商品"];
            }else{
                NSString * ids = [array componentsJoinedByString:@","];
                [BFShShopCarDataController stoneobs_fun_delete_shopcar_with_c_ids:ids handle:^(NSError *error, BOOL success, NSDictionary *resp) {
                    if (success) {
                        weakSelf.page = 1;
                        [weakSelf stoneobs_fun_send_list_request];
                    }
                }];
            }
        }];
    }

}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return BFShShopCarTableViewCell.stoneobs_ui_cell_height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BFShShopCarTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BFShShopCarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    BFShShopCarModel * model = self.dataSouce[indexPath.row];
    cell.carModel = model;
    __weak typeof(self) weakSelf =  self;
    [cell.choseButton setClicAction:^(UIButton *sender) {
        model.cus_selected = !model.cus_selected;
        sender.selected = !sender.selected;
        [weakSelf stoneobs_fun_update_price_and_allButton_status];
    }];
    [cell.add_view setAutoaddViewDidChangeHandle:^(STTools_AutoAddView *autoAddView, NSString *didChangeText) {
        [BFShShopCarDataController stoneobs_fun_change_shopcar_with_c_id:model.s_id num:didChangeText handle:^(NSError *error, BOOL success, NSDictionary *resp) {
            if (success) {
                model.num = didChangeText.integerValue;
                [weakSelf stoneobs_fun_update_price_and_allButton_status];
            }
        }];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BFShShopCarModel * model = self.dataSouce[indexPath.row];
    [TMUtils goto_good_detail_witdh_id:model.goods_id];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Private Method
- (CGFloat)stoneobs_fun_update_price_and_allButton_status{
    BOOL is_all = YES;
    CGFloat sum = 0;
    for (BFShShopCarModel * model in self.dataSouce) {
        if (!model.cus_selected) {
            is_all = NO;
        }else{
            sum = model.goods_price* model.num + sum;
        }
    }
    if (self.dataSouce.count == 0) {
        is_all = NO;
    }
    self.priceLable.text = [NSString stringWithFormat:@"合计:%0.2f",sum];
    NSString * sub = [NSString stringWithFormat:@"%0.2f",sum];
    self.priceLable.attributedText = [self.priceLable.text stoneobs_fun_st_convertAttributeStringWithKeyWord:sub attributes:@{NSForegroundColorAttributeName:FlatRed}];
    if (is_all) {
        self.allButton.selected = YES;
    }else{
        self.allButton.selected = NO;
    }
    
//    stoneobs_fun_update_price_and_allButton_status
    ({
        CGFloat allpost = 0;
        for (BFShShopCarModel * model in self.dataSouce) {
            if (model.cus_selected) {
                allpost =  MAX(allpost, model.free_postage);
            }
        }
//        allpost = 10;
        if (allpost > 0 && sum > 0) {
            self.postLable.hidden = NO;
            CGFloat value = sum - allpost;
            if (value > 0) {
                self.postLable.text = [NSString stringWithFormat:@"满%.1f包邮,已满足条件",allpost];
            }else{
                self.postLable.text = [NSString stringWithFormat:@"满%.1f包邮,还差%.1f",allpost,ABS(value)];
            }
            
        }else{
            self.postLable.hidden = YES;
        }
        
    });
    
    return sum;
}
- (NSArray*)stoneobs_fun_get_selctedids{
    NSMutableArray * array = NSMutableArray.new;
    for (BFShShopCarModel * model in self.dataSouce) {
        if (model.cus_selected) {
            [array addObject:model.s_id];
        }
    }
    return array.copy;
}
#pragma mark --stoneobs Action Method
- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    self.editButton.selected = !self.editButton.selected;
    [self stoneobs_ui_refresh_bootom_view];
    [self.bootom_view stoneobs_fun_st_showAnimationWithType:STAnimationTypecube_stoneobs_enum];
}

#pragma mark --stoneobs_net netWork Method
- (void)stoneobs_ui_config_refresh_footer{
    
}
- (void)stoneobs_fun_send_list_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/goods/carList"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumGet
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSArray * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        NSArray * objArray = [BFShShopCarModel mj_objectArrayWithKeyValuesArray:stoneobs_net_model_dic];
        if (self.page == 1) {
            self.dataSouce = NSMutableArray.new;
            [self.tableView.mj_header endRefreshing];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        [self.dataSouce addObjectsFromArray:objArray];
        [self.tableView reloadData];
        [self stoneobs_fun_update_price_and_allButton_status];
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        if (self.page == 1) {
            [self.tableView.mj_header endRefreshing];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
